#pragma once
#include <iostream>
#include <memory>
#include <functional>
#include <sys/wait.h>
#include "Socket.hpp"

using namespace SocketModule;
using task_t = std::function<void(std::shared_ptr<Socket>& sock, Inet_Addr addr)>;
class TcpServer
{
public:
    TcpServer(uint16_t port)
    :_port(port),
     _listensocketptr(std::make_unique<TcpSocket>()),
     _isruning(false)
    {
        _listensocketptr->BuildTcpServerSocketMethod(_port);
    }
    void Start(task_t _func)
    {
        
        _isruning = true;
        while(_isruning)
        {
            Inet_Addr addr;
            auto sock = _listensocketptr->Accept(&addr);
            pid_t pid = fork();
            if(pid < 0)
            {
                LOG(LogLevel::FATAL) << "fork error";
                exit(FORK_ERR);
            }
            else if(pid == 0)
            {
                
                _listensocketptr->Close();
                if(fork() > 0)
                {
                    exit(OK);
                }
                
                _func(sock, addr);
                sock->Close();
                exit(OK);
            }
            else
            {
                sock->Close();
                int rid = waitpid(pid, nullptr, 0);
                (void) rid;
            }

        }
        _isruning = false;
    }
private:
    std::unique_ptr<Socket> _listensocketptr;
    uint16_t _port;
    bool _isruning;
};